package me.hyman.testcustomview.pullToLoadDetail;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.Scroller;

import me.hyman.testcustomview.util.Logger;

/**
 * Created by Hyman on 2016/9/18.
 */
public class PullUpToLoadDetailViewGroup extends ViewGroup {


    private VelocityTracker velocityTracker;
    private MyScrollView firstScrollView, secondScrollView;

    private int scaledTouchSlop;

    private Scroller scroller;

    private boolean firstViewInBottom = false;
    private boolean secondViewInTop = false;
    private boolean isIntercepted = false;

    private int speed = 200;

    private int currentPosition = 0;
    private int firstViewBottomPos;
    private int lastY;

    public PullUpToLoadDetailViewGroup(Context context) {
        super(context);
        init();
    }

    public PullUpToLoadDetailViewGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public PullUpToLoadDetailViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        velocityTracker = VelocityTracker.obtain();
        scroller = new Scroller(getContext());
        scaledTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        //防止子View禁止父view拦截事件
        requestDisallowInterceptTouchEvent(false);

        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {

        int y = (int) ev.getY();

        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastY = y;
                break;

            case MotionEvent.ACTION_MOVE:

                if(firstViewInBottom) {
                    int dy = lastY - y;

                    // 当前第一个view已到达底部，并且是在向上滑动，滑动距离大于最小滑动距离
                    if(dy > scaledTouchSlop && currentPosition == 0) {
                        isIntercepted = true;
                        lastY = y;
                    }
                }

                if(secondViewInTop) {
                    int dy = lastY - y;

                    // 当前第二个view已到达顶部，并且是在向下滑动，滑动距离的绝对值大于最小滑动距离
                    if(dy < 0 && currentPosition == 1) {
                        if(Math.abs(dy) >= scaledTouchSlop) {
                            isIntercepted = true;
                        }
                    }
                }

                //Logger.d("isIntercepted: " + isIntercepted);

                break;
        }

        return isIntercepted;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        int y = (int) event.getY();
        velocityTracker.addMovement(event);

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastY = y;
                break;

            case MotionEvent.ACTION_MOVE:

                int dy = lastY - y;

                Logger.d("getScrollY: " + getScrollY() + ", dy: " + dy);

                if (getScrollY() + dy < 0) {
                    dy = getScrollY() + dy + Math.abs(getScrollY() + dy);
                }

                if (getScrollY() + dy + getHeight() > secondScrollView.getBottom()) {
                    dy = dy - (getScrollY() + dy - (secondScrollView.getBottom() - getHeight()));
                }

                Logger.e("dy: " + dy);

                scrollBy(0, dy*2/5);

                break;

            case MotionEvent.ACTION_UP:

                Logger.e("come in action_up");

                isIntercepted = false;
                velocityTracker.computeCurrentVelocity(1000);
                float yVelocity = velocityTracker.getYVelocity();

                if (currentPosition == 0) {
                    if (yVelocity < 0 && yVelocity < -speed) {
                        smoothScroll(firstViewBottomPos);
                        currentPosition = 1;
                    } else {
                        smoothScroll(0);
                    }
                } else {
                    if (yVelocity > 0 && yVelocity > speed) {
                        smoothScroll(0);
                        currentPosition = 0;
                    } else {
                        smoothScroll(firstViewBottomPos);
                    }
                }

                break;
        }

        return true;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        measureChildren(widthMeasureSpec, heightMeasureSpec);

        firstScrollView = (MyScrollView) getChildAt(0);
        secondScrollView = (MyScrollView) getChildAt(1);

        firstScrollView.setScrollListener(new MyScrollView.MyScrollListener() {
            @Override
            public void onScrollTop() {

            }

            @Override
            public void onScrollBottom(boolean atBottom) {
                firstViewInBottom = atBottom;
            }

            @Override
            public void onScroll(int scrollY) {

            }
        });

        secondScrollView.setScrollListener(new MyScrollView.MyScrollListener() {
            @Override
            public void onScrollTop() {

            }

            @Override
            public void onScrollBottom(boolean atBottom) {

            }

            @Override
            public void onScroll(int scrollY) {
                if (scrollY == 0) {
                    secondViewInTop = true;
                } else {
                    secondViewInTop = false;
                }
            }
        });

        firstViewBottomPos = firstScrollView.getBottom();
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        int childCount = getChildCount();
        int childTop = top;
        for (int i=0; i<childCount; i++) {
            View child = getChildAt(i);
            child.layout(left, childTop, right, childTop + child.getMeasuredHeight());
            childTop += child.getMeasuredHeight();
        }
    }

    private void smoothScroll(int destY) {
        int dy = destY - getScrollY();
        scroller.startScroll(getScrollX(), getScrollY(), 0, dy);
        invalidate();
    }

    @Override
    public void computeScroll() {
        if(scroller.computeScrollOffset()) {
            scrollTo(scroller.getCurrX(), scroller.getCurrY());
            postInvalidate();
        }
    }
}
